from dto import HelloResponse
from sqlalchemy import text
from db import get_session
 

class HelloHandler:
    def __init__(self, name: str):
        self.name = name
    
    def say_hello(self):
        return HelloResponse(
            message=f"Hello, {self.name}!")
    
    def query_mysql(self):
        # 使用 get_session() 获取数据库会话
        session = next(get_session())  # next() 获取生成器的值
        # 执行数据库查询操作
        try:
            # 使用 text() 包装 SQL 语句
            res = session.execute(text("SELECT * FROM users"))
            
            users = []
            for row in res:
                users.append({
                    "id": row[0],
                    "name": row[1],
                    "age": row[2]
                })
            
            return {"users": users, "count": len(users)}
            
        except Exception as e:
            print(f"数据库查询错误: {e}")
            return {"error": str(e)}
        finally:
            session.close()
